package com.triangle.cashier;


import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.triangle.cashier.adapter.SelectedGoodsAdapter;
import com.triangle.cashier.bean.ActionItem;
import com.triangle.cashier.bean.Order;
import com.triangle.cashier.bean.PayResult;
import com.triangle.cashier.bean.SelectedGoodsItem;
import com.triangle.cashier.tools.ConstUtil;
import com.triangle.cashier.tools.StringUtil;
import com.triangle.cashier.tools.Utils;
import com.triangle.cashier.widget.ConfirmDialog;
import com.triangle.cashier.widget.ExpendPopup;
import com.triangle.cashier.widget.PayResultDialog;
import com.triangle.cashier.widget.PendingOrderDialog;
import com.triangle.cashier.widget.PendingOrderSystem;
import com.triangle.cashier.widget.SelectMemberDialog;
import com.triangle.cashier.widget.VersionDialog;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private ListView listView;
    private SelectedGoodsAdapter selectedGoodsAdapter;
    private List<SelectedGoodsItem> list;
    private Order order;//订单
    private TextView totalTextView;//合计
    private TextView saleTextView;//折扣
    private EditText realTextView;//实收
    private EditText receivableTextView;//应收
    private TextView changeTextView;//找零
    private TextView memberBalanceTextView;//会员余额
    private TextView memberNumberTextView;//会员号
    private SelectMemberDialog memberDialog;
    private PayResultDialog payResultDialog;
    private PendingOrderDialog pendingOrderDialog;
    private PendingOrderSystem pendingOrderSystem;
    private ExpendPopup turnDutyPopup;
    private EditText codeEditText;
    private EditText currentEdit;
    private VersionDialog versionDialog;
    private ConfirmDialog confirmDialog;
    private boolean refreshReal = true; //刷新实收金额

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); //隐藏状态栏
        setTheme(android.R.style.Theme_Material_Dialog_Presentation);
        setContentView(R.layout.activity_main);
        initView();
        initData();
        CustomerEngine.getInstance(this).setProductList(order);
    }

    /**
     * 初始化界面
     */
    private void initView() {
        listView = (ListView) findViewById(R.id.goods_listView);
        totalTextView = (TextView) findViewById(R.id.total_TextView);
        saleTextView = (TextView) findViewById(R.id.sale_textView);
        receivableTextView = (EditText) findViewById(R.id.receivable_textView);
        realTextView = (EditText) findViewById(R.id.real_textView);
        changeTextView = (TextView) findViewById(R.id.change_textView);
        memberBalanceTextView = (TextView) findViewById(R.id.member_balance_TV);
        memberNumberTextView = (TextView) findViewById(R.id.member_number_TV);
        codeEditText = (EditText) findViewById(R.id.code_editText);
        codeEditText.setOnFocusChangeListener(new android.view.View.
                OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    // 此处为得到焦点时的处理内容
                    currentEdit = codeEditText;
                } else {
                    // 此处为失去焦点时的处理内容
                }
            }
        });
        realTextView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    // 此处为得到焦点时的处理内容
                    currentEdit = realTextView;
                    realTextView.setText("");
                } else {
                    // 此处为失去焦点时的处理内容
                }
            }
        });
        if (android.os.Build.VERSION.SDK_INT <= 10) {
            realTextView.setInputType(InputType.TYPE_NULL);
            codeEditText.setInputType(InputType.TYPE_NULL);
        } else {
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
            try {
                Class<EditText> cls = EditText.class;
                Method setSoftInputShownOnFocus;
                setSoftInputShownOnFocus = cls.getMethod("setShowSoftInputOnFocus", boolean.class);
                setSoftInputShownOnFocus.setAccessible(true);
                setSoftInputShownOnFocus.invoke(realTextView, false);
                setSoftInputShownOnFocus.invoke(codeEditText, false);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


        realTextView.addTextChangedListener(new TextWatcher() {

            String beforeText;
            int beforeLength;
            int changeLength;

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                beforeText = s.toString();
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                currentEdit = realTextView;
                realTextView.setFocusable(true);
            }

            @Override
            public void afterTextChanged(Editable s) {
                String content = s.toString();
                if ((!beforeText.equals("0.0"))) {
                    beforeLength = beforeText.length();
                    changeLength = content.length();
                    if (beforeLength > 2 && beforeLength < changeLength) {
                        if (beforeText.charAt(beforeLength - 2) == '.') {
                            realTextView.setText(beforeText);
                            return;
                        }

                    }
                } else {

                }

                realTextView.setSelection(content.length());
                if (order != null) {

                    if (!beforeText.equals(content)) {
                        float aFloat = 0;
                        if (!StringUtil.isEmpty(content)) {
                            aFloat = Float.valueOf(content);
                        }

                        if (aFloat == 0) {
                            order.setRealPayStr("0.0");
                        }
                        beforeText = content;
                        if (content.length() != 0) {
//                            float aFloat = Float.valueOf(content);
//                            if (aFloat > (int) aFloat) {
//                                order.setRealPay(aFloat);
//                            } else {
//                                order.setRealPay((int) aFloat);
//                            }
                            refreshOrderInfo();
                        }


                    }


                }
            }
        });

        codeEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                currentEdit = codeEditText;
            }

            @Override
            public void afterTextChanged(Editable s) {
                String content = s.toString();
                codeEditText.setSelection(content.length());
            }
        });
    }


    /**
     * 初始化数据
     */
    private void initData() {
        list = new ArrayList<>();
        selectedGoodsAdapter = new SelectedGoodsAdapter(getApplicationContext(), list, new SelectedGoodsAdapter.OnChangeOnListener() {
            @Override
            public void refresh() {

            }

            @Override
            public void add(int position) {
                SelectedGoodsItem goodsItem = list.get(position);
                goodsItem.setCount((goodsItem.getCount() + 1));
                goodsItem.setTotal(goodsItem.getCount() * goodsItem.getPrice());
                refreshReal = false;
                refreshOrderInfo();
            }

            @Override
            public void reduce(int position) {
                SelectedGoodsItem goodsItem = list.get(position);
                if (goodsItem.getCount() > 1) {
                    goodsItem.setCount((goodsItem.getCount() - 1));
                    goodsItem.setTotal(goodsItem.getCount() * goodsItem.getPrice());
                    refreshReal = false;
                    refreshOrderInfo();
                }
            }

            @Override
            public void delete(int position) {
                list.remove(position);
                refreshReal = false;
                refreshOrderInfo();
            }
        });
        listView.setAdapter(selectedGoodsAdapter);

    }

    /***
     * 添加选择商品
     * 模拟数据
     */
    private void addSelectedGoods() {

        if (order == null) {
            order = new Order();
        }
        if (list == null) {
            list = new ArrayList<>();
            order.setOrderNum("00001111");//模拟数据
            order.setDiscount(95);
        }
        order.setList(list);
        order.setOrderTime(StringUtil.getTimeFormatA(System.currentTimeMillis()));
        order.setDiscount(95);
        int size = list.size();
        SelectedGoodsItem item = new SelectedGoodsItem();
        item.setName("商品" + (size + 1));
        item.setCount(1);
        item.setNum("0000000000" + (size + 1));
        item.setPrice(5.3F);
        item.setTotal(item.getPrice() * item.getCount());
        list.add(item);
        refreshOrderInfo();
    }


    /**
     * 刷新订单信息
     */
    private void refreshOrderInfo() {
        float total = 0;
        for (int i = 0; i < list.size(); i++) {
            SelectedGoodsItem goodsItem = list.get(i);
            total += goodsItem.getTotal();
        }

        order.setTotal(Utils.double2Float(total));
        order.setReceivablePay(Utils.double2Float(order.getTotal() * (order.getDiscount() / 100f)));
        totalTextView.setText(order.getTotal() + "");
        saleTextView.setText(order.getDiscount() + "");
        receivableTextView.setText(order.getReceivablePay() + "");
        order.setRealPayStr(realTextView.getText().toString());
        if (refreshReal) {

        } else {
            refreshReal = true;
        }
        float change;
        if (StringUtil.isEmpty(order.getRealPayStr())) {
            change = Float.valueOf(0 - order.getReceivablePay());
        } else {
            change = Float.valueOf(order.getRealPayStr()) - order.getReceivablePay();
        }

        order.setChange(change);
        changeTextView.setText(order.getChange() + "");
        if (order.getChange() > 0) {
            changeTextView.setTextColor(getResources().getColor(R.color.main_change_ok));
        } else {
            if (order.getPayWay() == ConstUtil.PayWay.CASH) {
                changeTextView.setTextColor(getResources().getColor(R.color.main_change_fail));
            } else {
                changeTextView.setTextColor(getResources().getColor(R.color.main_change_ok));
            }

        }

        selectedGoodsAdapter.notifyDataSetChanged();
        CustomerEngine.getInstance(this).refresh(order);
    }


    public void keyOnClickEvent(View view) {
        if (currentEdit == null)
            return;
        String code = currentEdit.getText().toString();
        if (currentEdit == realTextView) {
            if (order == null)
                return;

            if (order.getPayWay() != ConstUtil.PayWay.CASH)
                return;


        }

        int id = view.getId();
        switch (id) {
            case R.id.key_0:

                if (currentEdit == realTextView) {
                    if (StringUtil.isEmpty(code)) {

                    } else {
                        if (code.equals("0") || code.equals("00")) {
                            code = "0";
                        } else {
                            code = code + "0";
                        }
                    }
                } else {
                    code = code + "0";
                }


                break;
            case R.id.key_1:

                code = code + "1";

                break;
            case R.id.key_2:

                code = code + "2";

                break;
            case R.id.key_3:

                code = code + "3";

                break;
            case R.id.key_4:

                code = code + "4";

                break;
            case R.id.key_5:

                code = code + "5";

                break;
            case R.id.key_6:

                code = code + "6";

                break;
            case R.id.key_7:

                code = code + "7";

                break;
            case R.id.key_8:

                code = code + "8";

                break;
            case R.id.key_9:

                code = code + "9";

                break;
            case R.id.key_00:
                if (currentEdit == realTextView) {
                    if (StringUtil.isEmpty(code)) {

                    } else {
                        if (code.equals("0") || code.equals("00")) {
                            code = "0";
                        } else {
                            if (code.contains(".")) {
                                code = code + "0";
                            } else {
                                code = code + "00";
                            }

                        }
                    }
                } else {
                    code = code + "00";
                }

                break;
            case R.id.key_point:

                if (currentEdit == codeEditText) {

                } else if (currentEdit == realTextView) {
                    if (!StringUtil.isEmpty(code)) {
                        code = code + ".";
                    } else {
                        code = "0";
                    }
                }


                break;
            case R.id.key_100:
                if (currentEdit == codeEditText) {

                } else if (currentEdit == realTextView) {
                    code = "100";
                }
                break;
            case R.id.key_50:
                if (currentEdit == codeEditText) {

                } else if (currentEdit == realTextView) {
                    code = "50";
                }
                break;
            case R.id.key_20:
                if (currentEdit == codeEditText) {

                } else if (currentEdit == realTextView) {
                    code = "20";
                }
                break;
            case R.id.key_10:
                if (currentEdit == codeEditText) {

                } else if (currentEdit == realTextView) {
                    code = "10";
                }
                break;
        }

        currentEdit.setText(code);
    }


    /**
     * 查询条形码
     *
     * @param view v
     */
    public void searchCodeEvent(View view) {
        refreshReal = false;
        addSelectedGoods();
        codeEditText.setFocusable(false);
    }

    /**
     * 清空商品事件
     *
     * @param v view
     */
    public void clearGoodsEvent(View v) {
        if(list.size() <=0){
            return;
        }
        confirmDialog = new ConfirmDialog(getResources().getString(R.string.clear_title),
                getResources().getString(R.string.clear_content),
                new ConfirmDialog.ConfirmResultClickListener() {
                    @Override
                    public void cancel() {
                        confirmDialog.dismiss();
                    }

                    @Override
                    public void ok() {
                        list.clear();
                        order = null;
                        totalTextView.setText("0.0");
                        changeTextView.setText("0.0");
                        realTextView.setText("0.0");
                        selectedGoodsAdapter.notifyDataSetChanged();
                        CustomerEngine.getInstance(MainActivity.this).refresh(order);
                    }
                });
        confirmDialog.show(getFragmentManager(), "");
    }


    /**
     * 增加商品事件
     *
     * @param v view
     */
    public void addGoodsEvent(View v) {

        startActivityForResult(new Intent(getApplicationContext(), ProductListActivity.class), 0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        refreshReal = false;
        addSelectedGoods();
    }


    /**
     * 现金支付
     *
     * @param v view
     */
    public void cashPayEvent(View v) {
        currentEdit = realTextView;
        realTextView.setText("0");
        realTextView.setFocusable(true);
        realTextView.requestFocus();
        if (order != null) {
            order.setPayWay(ConstUtil.PayWay.CASH);
            realTextView.setText("");
        }

    }

    /**
     * 支付宝支付
     *
     * @param v view
     */
    public void aliPayEvent(View v) {
        if (order != null) {
            order.setPayWay(ConstUtil.PayWay.ALI_PAY);
        }
    }

    /**
     * 微信支付
     *
     * @param v view
     */
    public void weChatPayEvent(View v) {
        if (order != null) {
            order.setPayWay(ConstUtil.PayWay.WE_CHAT);
        }
    }

    /**
     * 银行卡支付
     *
     * @param v view
     */
    public void bankCardPayEvent(View v) {
        if (order != null) {
            order.setPayWay(ConstUtil.PayWay.BACK_CARD);
        }
    }

    /**
     * 村村通支付
     *
     * @param v view
     */
    public void cctPayEvent(View v) {
        if (order != null) {
            order.setPayWay(ConstUtil.PayWay.CTT);
        }
    }


    /**
     * 扎账事件
     *
     * @param view v
     */
    public void statisticalAccountsEvent(View view) {

    }

    /**
     * 弹出钱箱事件
     *
     * @param view v
     */
    public void popCashBoxEvent(View view) {

    }

    /**
     * 挂单事件
     *
     * @param v v
     */
    public void pendingOrderEvent(View v) {

        pendingOrderDialog = new PendingOrderDialog("", new PendingOrderDialog.OnPendingResultClickListener() {
            @Override
            public void cancel() {
                pendingOrderDialog.dismiss();
            }

            @Override
            public void ok(String orderNote, String note) {
                pendingOrderDialog.dismiss();
            }
        });
        pendingOrderDialog.show(getFragmentManager(), "");
    }

    /**
     * 取单事件
     *
     * @param view v
     */
    public void takeOrderEvent(View view) {
        pendingOrderSystem = new PendingOrderSystem(new PendingOrderSystem.OnPendingClickListener() {
            @Override
            public void cancel() {
                pendingOrderSystem.dismiss();
            }

            @Override
            public void delete() {

                pendingOrderSystem.dismiss();
                // TODO: 2018/7/6 删除订单
            }

            @Override
            public void ok(int position) {
                pendingOrderSystem.dismiss();
            }
        });
        pendingOrderSystem.show(getFragmentManager(), "");
    }

    /**
     * 主菜单事件
     *
     * @param view v
     */
    public void menuEvent(View view) {
        turnDutyPopup = new ExpendPopup(getApplication(), ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT, 0);
        turnDutyPopup.setItemOnClickListener(new ExpendPopup.OnItemOnClickListener() {
            @Override
            public void onItemClick(ActionItem item, int position, int selectedIndex) {
                if (position == 0) {
                    //show update pw page
                    startActivity(new Intent(getApplicationContext(), UpdatePWDActivity.class));
                } else if (position == 1) {
                    // TODO: 2018/7/6 交接班次
                } else if (position == 2) {
                    //show version dialog
                    showVersionDialog();
                }
            }
        });

        turnDutyPopup.addAction(new ActionItem(getApplication(), R.string.main_modify_password,
                R.drawable.modify_password));
        turnDutyPopup.addAction(new ActionItem(getApplication(), R.string.main_turn_duty,
                R.drawable.turn_duty));
        turnDutyPopup.addAction(new ActionItem(getApplication(), R.string.main_version,
                R.drawable.version));
        turnDutyPopup.show(view);
    }

    /***
     * 退出登录事件
     *
     * @param v v
     */
    public void logOutEvent(View v) {
        onBackPressed();
    }

    /**
     * 展示版本对话框
     */
    private void showVersionDialog() {
        versionDialog = new VersionDialog(new VersionDialog.VersionResultClickListener() {
            @Override
            public void ok() {
                versionDialog.dismiss();
            }
        });
        versionDialog.show(getFragmentManager(), "");
    }

    /**
     * 结算事件
     *
     * @param v v
     */
    public void settlementEvent(View v) {

        if (order == null)
            return;

        if (order.getPayWay() == ConstUtil.PayWay.NULL)
            return;
        realTextView.setFocusable(false);
        if (currentEdit != null)
            currentEdit.setFocusable(false);
        currentEdit = null;
        PayResult payResult = new PayResult(false, 365.5F, 1, "3154 1215 1212 3252", "2018-6-12 12:36:56");
        payResultDialog = new PayResultDialog(payResult, new PayResultDialog.OnPayResultClickListener() {
            @Override
            public void cancel() {
                payResultDialog.dismiss();
            }

            @Override
            public void ok() {
                payResultDialog.dismiss();
            }
        });
        payResultDialog.show(getFragmentManager(), "");
    }

    /***
     * 键盘上删除事件
     *
     * @param view v
     */
    public void keyDeleteEvent(View view) {
        if (currentEdit != null) {
            if (currentEdit == codeEditText) {
                String s = codeEditText.getText().toString();
                if (s.length() > 0) {
                    codeEditText.setText(s.substring(0, s.length() - 1));
                }
            } else if (currentEdit == realTextView) {
                String s = realTextView.getText().toString();
                if (s.length() > 0) {
                    realTextView.setText(s.substring(0, s.length() - 1));
                    s = realTextView.getText().toString();
                    int length = s.length();

                    if (length > 0 && s.indexOf(".") == length - 1) {
                        realTextView.setText(s.substring(0, s.length() - 1));
                    }
                }
                s = realTextView.getText().toString();
                if (StringUtil.isEmpty(s)) {
                    realTextView.setText("0");
                }
            }
        }
    }

    /**
     * 键盘清空按钮
     *
     * @param view v
     */
    public void keyClearEvent(View view) {
        if (currentEdit != null) {
            if (currentEdit == codeEditText) {
                codeEditText.setText("");
            } else if (realTextView == currentEdit) {
                currentEdit.setText("");
            }
        }

    }

    public void selectMemberEvent(View view) {
        memberDialog = new SelectMemberDialog(this, new SelectMemberDialog.OnChangeSelectedClickListener() {
            @Override
            public void cancel() {
                memberDialog.dismiss();
            }

            @Override
            public void ok() {
                memberDialog.dismiss();
            }
        });
        memberDialog.show(getFragmentManager(), "");

    }

    @Override
    public void onBackPressed() {
        confirmDialog = new ConfirmDialog(getResources().getString(R.string.quit_title),
                getResources().getString(R.string.quit_content),
                new ConfirmDialog.ConfirmResultClickListener() {
                    @Override
                    public void cancel() {
                        confirmDialog.dismiss();
                    }

                    @Override
                    public void ok() {
                        Intent startMain = new Intent(Intent.ACTION_MAIN);
                        startMain.addCategory(Intent.CATEGORY_HOME);
                        startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(startMain);
                        System.exit(0);
                    }
                });
        confirmDialog.show(getFragmentManager(), "");

    }
}
